import { TransactionType } from "@mallfoundry/finance"
import { Button, Card, Col, DatePicker, Form, Radio, Row, Select, Space } from "antd"
import { RadioChangeEvent } from "antd/lib/radio"
import * as dayjs from "dayjs"
import * as _ from "lodash"
import * as React from "react"
import { useEffect, useState } from "react"
import { useHistory, useLocation, useParams } from "react-router-dom"
import Page from "../../components/page"
import { useTransactions } from "../../hooks/finance"
import { useStore } from "../../hooks/store"
import classes from "./transaction-list.module.scss"
import TransactionTable from "./transaction-table"

const { RangePicker } = DatePicker

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
}


export default function TransactionList() {
  const history = useHistory()
  const location = useLocation()
  const searchParams = new URLSearchParams(location.search)
  const page = searchParams.get("page") ?? 1
  const limit = searchParams.get("limit") ?? 20
  const types = searchParams.get("types") ?? ""
  const createdTimeStart = searchParams.get("created_time_start") ?? ""
  const createdTimeEnd = searchParams.get("created_time_end") ?? ""
  const [customCreatedTimes, setCustomCreatedTimes] = useState(0)

  const { storeId } = useParams<{ storeId: string }>()

  const { loading: storeLoading, store: { accountId } } = useStore(storeId)

  const {
    loading: transactionsLoading,
    elements: transactions,
  } = useTransactions({
    page, limit,
    accountId, types,
  })

  const loading = storeLoading || transactionsLoading

  const [form] = Form.useForm()

  useEffect(() => {
    form.setFieldsValue({
      types,
      createdTimes: [
        createdTimeStart ? dayjs(createdTimeStart) : undefined,
        createdTimeEnd ? dayjs(createdTimeEnd) : undefined,
      ],
    })
    handleSetCustomCreatedTimes([createdTimeStart, createdTimeEnd])
  }, [form, types, createdTimeStart, createdTimeEnd])

  function handleChangeCreatedTimes(e: RadioChangeEvent) {
    const aCustomCreatedTimes = e.target.value
    setCustomCreatedTimes(aCustomCreatedTimes)
    if (aCustomCreatedTimes === -7) {
      form.setFieldsValue({ createdTimes: [dayjs().add(-6, "day"), dayjs()] })
    } else if (aCustomCreatedTimes === -30) {
      form.setFieldsValue({ createdTimes: [dayjs().add(-29, "day"), dayjs()] })
    }
  }

  function handleSetCustomCreatedTimes(dateStrings: [string, string]) {
    const [dateStart, dateEnd] = dateStrings
    const today = dayjs().format("YYYY-MM-DD")
    const in7day = dayjs().add(-6, "day").format("YYYY-MM-DD")
    const in30day = dayjs().add(-29, "day").format("YYYY-MM-DD")
    if (dateStart === in7day && dateEnd === today) {
      setCustomCreatedTimes(-7)
    } else if (dateStart === in30day && dateEnd === today) {
      setCustomCreatedTimes(-30)
    } else {
      setCustomCreatedTimes(0)
    }
  }

  function handleSearch() {
    form.validateFields()
      .then(values => {
        const { types, createdTimes } = values
        if (types) {
          searchParams.set("types", types)
        } else {
          searchParams.delete("types")
        }
        if (createdTimes) {
          const [createdTimeStart, createdTimeEnd] = createdTimes
          if (createdTimeStart) {
            searchParams.set("created_time_start", dayjs(createdTimeStart).format("YYYY-MM-DD"))
          } else {
            searchParams.delete("created_time_start")
          }
          if (createdTimeEnd) {
            searchParams.set("created_time_end", dayjs(createdTimeEnd).format("YYYY-MM-DD"))
          } else {
            searchParams.delete("created_time_end")
          }
        } else {
          searchParams.delete("created_time_start")
          searchParams.delete("created_time_end")
        }
        history.replace(_.assign(location, {
          search: `?${searchParams.toString()}`,
        }))
      })
  }

  function handleReset() {
    history.push(_.assign(location, {
      search: ``,
    }))
  }

  return (
    <div className={classes.TransactionList}>
      <Page.Header title="交易记录" ghost={false}/>
      <Page.Content>
        <Card>
          <Row gutter={[16, 16]}>
            <Col span={24}>
              <Card className={classes.FilterBar} bordered={false}>
                <Form {...layout} form={form}>
                  <Row>
                    <Col span={6}>
                      <Form.Item label="交易时间" name="createdTimes">
                        <RangePicker style={{ width: "100%" }}
                                     onChange={(dates, dateStrings) => handleSetCustomCreatedTimes(dateStrings)}/>
                      </Form.Item>
                    </Col>
                    <Col span={6}>
                      <Radio.Group style={{ marginLeft: "8px" }} value={customCreatedTimes} onChange={handleChangeCreatedTimes}>
                        <Space>
                          <Radio.Button value={-7} className={classes.PlacedDateButton}>近7天</Radio.Button>
                          <Radio.Button value={-30} className={classes.PlacedDateButton}>近30天</Radio.Button>
                        </Space>
                      </Radio.Group>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={6}>
                      <Form.Item name="types" label="交易类型">
                        <Select>
                          <Select.Option value="">全部</Select.Option>
                          <Select.Option value={TransactionType.Payment}>支付</Select.Option>
                          <Select.Option value={TransactionType.Withdrawal}>提现</Select.Option>
                          <Select.Option value={TransactionType.Topup}>充值</Select.Option>
                          <Select.Option value={TransactionType.Transfer}>转账</Select.Option>
                        </Select>
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={6}>
                      <Row>
                        <Col offset={6}>
                          <Space>
                            <Button type="primary" onClick={handleSearch} loading={loading}>筛选</Button>
                            <Button onClick={handleReset}>重置</Button>
                          </Space>
                        </Col>
                      </Row>
                    </Col>
                  </Row>
                </Form>
              </Card>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <TransactionTable loading={loading} dataSource={transactions}/>
            </Col>
          </Row>
        </Card>
      </Page.Content>
    </div>
  )
}
